package io.bdmc.modules.bss.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.bdmc.common.annotation.SysLogger;
import io.bdmc.common.enums.RouteTypeEnum;
import io.bdmc.common.utils.Constant;
import io.bdmc.common.utils.R;
import io.bdmc.common.utils.StringUtils;
import io.bdmc.core.snmp.cache.ConcurrentHashMapCacheUtils;
import io.bdmc.modules.bss.entity.DeviceFibreMatch;
import io.bdmc.modules.bss.entity.DeviceMeasure;
import io.bdmc.modules.bss.entity.DeviceRoute;
import io.bdmc.modules.bss.service.IDeviceFibreMatchService;
import io.bdmc.modules.bss.service.IDeviceMeasureEventService;
import io.bdmc.modules.bss.service.IDeviceMeasureService;
import io.bdmc.modules.bss.service.IDeviceRouteService;
import io.bdmc.modules.sys.controller.AbstractController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

//import org.apache.shiro.authz.annotation.RequiresPermissions;

/**
 * <p>
 * 路由 前端控制器
 * </p>
 *
 * @author 黄露
 * @since 2021-05-21
 */

// "路由", description = "路由")
@RestController
@RequestMapping("/bss/route")
public class DeviceRouteController extends AbstractController {

	@Autowired
	IDeviceRouteService routeService;

	@Autowired
	IDeviceMeasureService measureService;

	@Autowired
	IDeviceMeasureEventService measureEventService;

	@Autowired
	IDeviceFibreMatchService matchService;

	// @GetMapping("/list")
	// @ApiOperation(value="分页查询路由", notes="分页查询路由")
	// @RequiresPermissions("bss:deviceRoute:list")
	// public R list(DeviceRouteParam params) {
	// MyPage<DeviceRoute> myPage = new MyPage<DeviceRoute>(params.getCurrent(),
	// params.getSize());
	// myPage = _devicerouteSvs.mySelectPage(myPage, params);
	// return R.ok().putPageData(myPage.getRecords(), myPage.getTotal());
	//
	// }

	@SysLogger("新增路由")
	@PostMapping("/add")
	// "新增路由", notes = "新增路由")
	public R add(@RequestBody DeviceRoute deviceroute) {
		deviceroute.setCreateBy(getUser().getUsername());
		deviceroute.setCreateTime(LocalDateTime.now());
		Boolean b = deviceroute.insert();
		return R.trueOrFalse(b);
	}

	@GetMapping("/devices")
	// "查询所有路由中包含的设备", notes = "查询路由")
	public R devices() {
		final List<DeviceRoute> list = routeService.list();
		List<String> snList = new ArrayList<>();
		for (DeviceRoute route : list) {
			switch(RouteTypeEnum.valueOf(route.getRouteType()) ){
			    case fspRoute:
					snList.add(route.getDeviceSnFrom());
					snList.add(route.getDeviceSnTo());
					if(StringUtils.isNotEmpty(route.getFmsSn())){
						snList.add(route.getFmsSn());
					}
			        break;
				case realTimeRoute:
					snList.add(route.getFmsSn());

					break;
				case offlineRoute:
					snList.add(route.getDeviceSnFrom());
					snList.add(route.getOswSn());
					snList.add(route.getOpmSn());
					break;
				case pollingRoute:
					snList.add(route.getDeviceSnFrom());
					snList.add(route.getOswSn());
					break;
			    default:
			        break;
			}

		}
		return R.ok().putData(snList);
	}

	@GetMapping("/info")
	// "查询路由", notes = "查询路由")
	public R list(int routeId) {
		return R.ok().putData(routeService.getById(routeId));
	}

	@SysLogger("修改路由")
	@PostMapping("/update")
	// "修改路由", notes = "修改路由")
	public R update(@RequestBody DeviceRoute deviceroute) {
		// 如果修改关闭自动测试，则删除缓存中的自动测试时间
		if (deviceroute.getAutoMeasureInterval() != null && deviceroute.getAutoMeasureInterval() < 1
				&& StringUtils.isNotEmpty(deviceroute.getFmsSn())) {
			if (ConcurrentHashMapCacheUtils.isExist(Constant.FmsDeviceAutoMeasureTime + deviceroute.getFmsSn())) {
				ConcurrentHashMapCacheUtils.deleteCache(Constant.FmsDeviceAutoMeasureTime + deviceroute.getFmsSn());
			}
		}
		if (deviceroute.getRouteType().equals("realTimeRoute")) {
			String str = Constant.routeOTDRAlarmTimes + deviceroute.getFmsSn();
			ConcurrentHashMapCacheUtils.deleteCache(str);
		}
		Boolean b = deviceroute.updateById();
		return R.trueOrFalse(b);
	}

	@PostMapping("/sor")
	public R updateSorType(@RequestBody DeviceRoute deviceroute){
		final DeviceRoute dbRoute = routeService.getById(deviceroute.getRouteId());
		dbRoute.setSorType(deviceroute.getSorType());
		final boolean b = dbRoute.updateById();
		return R.trueOrFalse(b);
	}

	@SysLogger("删除路由")
	@PostMapping("/delete")
	// "删除路由", notes = "删除路由")
	public R delete(@RequestBody Integer routeId) {
		DeviceRoute route = routeService.getById(routeId);
		if (route == null) {
			return R.ok();
		}
		if (StringUtils.isNotEmpty(route.getFmsSn())) {
			if (ConcurrentHashMapCacheUtils.isExist(Constant.MSP2000MeasureNowMapPrefix+ route.getFmsSn())) {
				return R.error("fms正在测试，无法删除");
			}
			if (ConcurrentHashMapCacheUtils.isExist(Constant.FmsDeviceAutoMeasureTime + ":" + route.getFmsSn())) {
				return R.error("fms正在周期测试，无法删除");
			}
		}
		if (StringUtils.isNotEmpty(route.getOswSn())) {
			if (ConcurrentHashMapCacheUtils.isExist(Constant.MSP2000MeasureNowMapPrefix+ route.getOswSn())) {
				return R.error("osw正在测试，无法删除");
			}
			if (ConcurrentHashMapCacheUtils.isExist(Constant.FmsDeviceAutoMeasureTime + ":" + route.getOswSn())) {
				return R.error("osw正在周期测试，无法删除");
			}
		}
		// 删除测量数据
		measureService.remove(new QueryWrapper<DeviceMeasure>().eq("route_id", routeId));
		// 删除绑定关系
		matchService.remove(new QueryWrapper<DeviceFibreMatch>().eq("route_id", route.getRouteId()));
		// measureEventService.remove(new
		// QueryWrapper<DeviceMeasureEvent>().eq("route_id", routeId));
		return R.trueOrFalse(routeService.deleteRoute(route));
	}
}
